from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.ecc.v20181213 import ecc_client, models
import json 
from termcolor import colored 
import base64

def correct_image(secret_id, secret_key, image_path):
    """图片作文批改接口"""
    try:
        # 初始化认证
        cred = credential.Credential(secret_id, secret_key)
        
        # 配置HTTP协议
        http_profile = HttpProfile()
        http_profile.endpoint = "ecc.tencentcloudapi.com"
        
        # 初始化客户端配置（新增）
        client_profile = ClientProfile()
        client_profile.httpProfile = http_profile
        
        # 修正参数名称（client_profile -> profile）
        client = ecc_client.EccClient(cred, "ap-guangzhou", profile=client_profile)

        # 读取图片并编码
        with open(image_path, "rb") as f:
            image_data = base64.b64encode(f.read()).decode('utf-8')

        # 构建图片批改请求
        req = models.CorrectMultiImageRequest()
        req.Image = [image_data]
        req.InputType = 1
        req.SessionId = "teacher_correction"
        req.Grade = "cet4"  # 新增必填参数：年级标准
        req.IsAsync = 0  # 新增必填参数：是否异步处理
        req.ServerType = 1  # 新增必填参数：服务器类型 1：“图像批改

        # req.Score = 100.0  # 删除无效参数
        
        # 发送请求
        response = client.CorrectMultiImage(req)
        return response
    except Exception as e:
        raise RuntimeError(f"图片批改失败: {str(e)}")


import json 
from termcolor import colored 
 
def display_friendly_result(api_response):
    try:
        data = json.loads(api_response) 
    except json.JSONDecodeError:
        print(colored("错误：无效的JSON格式", "red"))
        return
    
    # 修正数据路径（直接使用Response下的Data字段）
    # 第一层：获取Response对象
    result_data = data.get("ResultData", {})
    # 第二层：获取Data字段
    #result_data = response_data.get("Data", {})


    print(result_data)
    if not result_data.get("CorrectData"):
        print(colored("未找到有效批改数据", "yellow"))
        return
    
    # 显示基础信息 
    print(colored("\n=== 作文评分结果 ===", "cyan", attrs=["bold"]))
    
    # 提取评分数据（修正路径）
    correct_data = result_data["CorrectData"]
    
    print(f"任务ID: {result_data.get('TaskId',  '无')}")
    
    # 显示评分详情 
    correct_data = result_data.get("CorrectData",  {})
    if correct_data:
        print(colored("\n--- 综合评分 ---", "green"))
        print(f"总分: {colored(correct_data.get('Score',  0), 'yellow')}")
        print(f"评语: {colored(correct_data.get('Comment',  '无'), 'magenta')}")
        
        # 显示分类评分 
        score_cat = correct_data.get("ScoreCat",  {})
        if score_cat:
            print(colored("\n--- 分类评分 ---", "green"))
            categories = ["Words", "Sentences", "Structure", "Content"]
            for cat in categories:
                if cat in score_cat:
                    details = score_cat[cat]
                    print(f"{details.get('Name',  cat)}: "
                          f"{colored(details.get('Score',  0), 'yellow')}分 "
                          f"(权重: {details.get('Percentage',  0)}%)")
        
        # 显示句子级别建议 
        sentence_comments = correct_data.get("SentenceComments",  [])
        if sentence_comments:
            print(colored("\n--- 句子建议 ---", "green"))
            for i, comment in enumerate(sentence_comments, 1):
                sentence = comment.get("Sentence",  {})
                print(f"\n句子 {i} (段落{sentence.get('ParaID',  '?')}-句子{sentence.get('SentenceID',  '?')}):")
                print(f"原文: {colored(sentence.get('Sentence',  '无'), 'blue')}")
                
                suggestions = comment.get("Suggestions",  [])
                if suggestions:
                    print("建议:")
                    for sug in suggestions:
                        sug_type = sug.get("Type",  "建议")
                        color = "red" if sug_type == "Error" else "yellow"
                        print(f"  - {colored(sug.get('ErrorType',  '建议'), color)}: "
                              f"{sug.get('Message',  '无详细建议')}")
                        print(f"    原词: {colored(sug.get('Origin',  '无'), 'red')} → "
                              f"建议替换为: {colored(sug.get('Replace',  '无'), 'green')}")
 
# 示例使用 
api_response = """{
    "Response": {
        "ResultData": {
            "Content": "this is compostion content",
            "CorrectData": {
                "Score": 72.39,
                "ScoreCat": {
                    "Words": {
                        "Name": "词汇",
                        "Score": 76.08,
                        "Percentage": 42 
                    },
                    "Sentences": {
                        "Name": "句子",
                        "Score": 61.16,
                        "Percentage": 28 
                    },
                    "Structure": {
                        "Name": "篇章结构",
                        "Score": 80.37,
                        "Percentage": 23 
                    },
                    "Content": {
                        "Name": "内容",
                        "Score": 69,
                        "Percentage": 7 
                    },
                    "Score": 0,
                    "Percentage": 0 
                },
                "Comment": "作者词汇基础扎实；可适当增加复合句和从句的使用；文中衔接词丰富。请多加练习，更上一层楼。",
                "SentenceComments": [
                    {
                        "Sentence": {
                            "Sentence": "Teenagers likeating fast 1888861 food.",
                            "ParaID": 1,
                            "SentenceID": 7 
                        },
                        "Suggestions": [
                            {
                                "Type": "Error",
                                "ErrorType": "拼写错误",
                                "Origin": "likeating",
                                "Replace": "elevating",
                                "Message": "likeating 可能是拼写错误，请注意拼写检查，这里应将 likeating 替换为 elevating",
                                "ErrorPosition": [
                                    8,
                                    8 
                                ],
                                "ErrorCoordinates": [
                                    {
                                        "Coordinate": [
                                            424,
                                            360,
                                            459,
                                            359,
                                            459,
                                            386,
                                            424,
                                            387 
                                        ]
                                    }
                                ]
                            },
                            {
                                "Type": "Error",
                                "ErrorType": "易混淆词汇建议",
                                "Origin": "1888861",
                                "Replace": "1886861",
                                "Message": "注意1888861 与 1886861 的区别，推荐将 1888861 替换为 1886861",
                                "ErrorPosition": [
                                    8,
                                    8 
                                ],
                                "ErrorCoordinates": [
                                    {
                                        "Coordinate": [
                                            424,
                                            360,
                                            459,
                                            359,
                                            459,
                                            386,
                                            424,
                                            387 
                                        ]
                                    }
                                ]
                            }
                        ]
                    }
                ]
            },
            "TaskId": null 
        },
        "RequestId": "ae5d82c1-47a1-43c0-b8a2-4d3c35a21488"
    }
}"""
 

# display_friendly_result(api_response)

# 使用示例
if __name__ == "__main__":
    import configparser
    import os
    
    try:
        # 读取配置文件
        config = configparser.ConfigParser()
        config.read(r'd:\AiPro\english\config.ini')
        
        SECRET_ID = config.get('Tencent', 'secret_id')
        SECRET_KEY = config.get('Tencent', 'secret_key')
        IMAGE_PATH = "D:\AiPro\english\zuowen2.jpg"
        
        try:
            result = correct_image(SECRET_ID, SECRET_KEY, IMAGE_PATH)
            display_friendly_result(result.to_json_string())
            #print(result)
            exit(0)
            # 解析响应数据
            print(f"批改结果：{result.RequestId}")
            if hasattr(result, 'Data'):
                print(f"综合评分：{result.Data.TotalScore}")
                for error in result.Data.Errors:
                    print(f"错误位置：{error.StartPosition}-{error.EndPosition}")
                    print(f"错误类型：{error.TypeDescription}")
                    print(f"修改建议：{error.CorrectedText}")
        except Exception as e:
            print(e)
    except configparser.NoSectionError:
        print("配置错误：请在config.ini中创建[Tencent]段落")
    except configparser.NoOptionError as e:
        print(f"配置缺失：{str(e)}")
    except Exception as e:
        print(e)